﻿using Cdn.Blogger.Controllers;
using Cdn.Blogger.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;

namespace Cdn.Blogger.Data
{

    public partial class PortalEntities : DbContext
    {
        public PortalEntities()
            : base("name=PortalEntities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public DbSet<AppUser> AppUsers { get; set; }
    }

    public class UserService
    {
        PortalEntities db = new PortalEntities();
        static UserService keeper = new UserService();

        public static UserService Keeper
        {
            get { return UserService.keeper; }
            set { UserService.keeper = value; }
        }

        public string SimpleCode(string text)
        {
            return SimpleEncryption.MD5.UrlCode(text);
        }

        public string SimpleDeCode(string text)
        {
            return SimpleEncryption.MD5.UrlDeCode(text);
        }

        public long AddAppUser(string userName, string userEmail, string provider)
        {
            try
            {
                AppUser user = new AppUser();
                user.DateCreated = DateTime.Now;
                user.ProviderID = provider;
                user.Email = userEmail;
                user.UserName = userName;
                user.GlobalID = Guid.NewGuid().ToString();
                user.InWorkflow = (int)UserInWorkflowStatus.NewUser;
                db.AppUsers.Add(user);
                db.SaveChanges();

                SendVerificationNeededEmail(user);

                return user.AppUserID;
            }
            catch (Exception ex)
            {
            }
            return -1;
        }
        public void SendVerificationNeededEmail(AppUser user)
        {
            var saltedUser = UserService.Keeper.GetSaltedUser(user);
            string body = SimpleFormatter.EmailFormatter.GetEmailBodyForVerification(saltedUser);
            SimpleMail.Smtp.Send("administrator@authentication.com",
                    user.Email,
                    "Welcome to App",
                    body);
        }
        public AppUser GetAppUserFromSalt(string salt, int cachedDuration = 0)
        {
            if (cachedDuration > 0)
            {
                object o = SimpleCache.Web.Get<string>(salt);
                if (o == null)
                {
                    var user = db.AppUsers.Where(u => u.Salt.ToLower() == salt.ToLower()).FirstOrDefault();
                    SimpleCache.Web.Add(user, salt);
                    return user;
                }
                else
                {
                    return (AppUser)o;
                }
            }
            else
            {
                var user = db.AppUsers.Where(u => u.Salt.ToLower() == salt.ToLower()).FirstOrDefault();
                return user;
            }
        }
        public AppUser GetAppUser(string userEmail, int cachedDuration = 0)
        {
            if (cachedDuration > 0)
            {
                object o = SimpleCache.Web.Get<string>(userEmail);
                if (o == null)
                {
                    var user = db.AppUsers.Where(u => u.UserName.ToLower() == userEmail.ToLower()).FirstOrDefault();
                    SimpleCache.Web.Add(user, userEmail);
                    return user;
                }
                else
                {
                    return (AppUser)o;
                }
            }
            else
            {
                var user = db.AppUsers.Where(u => u.UserName.ToLower() == userEmail.ToLower()).FirstOrDefault();
                return user;
            }
        }

        public AppUser GetSaltedUser(AppUser user)
        {
            string secret2 = DateTime.Now.ToUniversalTime().ToString();
            string hashCode = SimpleCode(secret2);
            user.Salt = hashCode.Substring(0, 8);
            user.Secret = hashCode;
            SaveAppUser(user);
            return user;
        }


        public long SaveAppUser(AppUser user)
        {
            try
            {
                db.Set<AppUser>().Attach(user);
                db.Entry(user).State = System.Data.EntityState.Modified;
                db.SaveChanges();
                return user.AppUserID;
            }
            catch (Exception ex)
            {
            }
            return -1;
        }

    }
}